package com.heima.controller;

import com.heima.common.Result;
import com.heima.pojo.dto.SkuClassDto;
import com.heima.pojo.vo.SkuClassVo;
import com.heima.service.SkuClassService;
import com.heima.utils.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 赵超
 */
@RestController
@Slf4j
@RequestMapping("/api/vm-service/skuClass")
public class SkuClassController {
    @Autowired
    private SkuClassService skuClassService;

    @PostMapping
    public Boolean add(@RequestBody SkuClassDto skuClassDto) {
        skuClassService.add(skuClassDto);
        return true;
    }

    @GetMapping("/search")
    public PageResult<SkuClassVo> page(
            @RequestParam Integer pageIndex,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) String className
    ) {
        return skuClassService.page(pageIndex, pageSize, className);
    }

    @GetMapping("/{classId}")
    public SkuClassVo getSkuClassByClassId(@PathVariable String classId) {
        return skuClassService.getSkuClassByClassId(Integer.valueOf(classId));
    }

    @PutMapping("/{classId}")
    public Boolean updateSkuClassByClassId(@PathVariable String classId, @RequestBody SkuClassDto skuClassDto) {
        log.info("更新classId：{}，skuClassDto：{}", classId, skuClassDto);
        // 检查classId是否有效
        if (classId == null || "undefined".equals(classId) || classId.trim().isEmpty()) {
            log.error("classId无效");
            return false;
        }
        try {
            int classIdInt = Integer.parseInt(classId);
            skuClassDto.setClassId(classIdInt);
            int result = skuClassService.updateSkuClassByClassId(skuClassDto);
            log.info("更新结果：{}", result);
            return result > 0;
        } catch (NumberFormatException e) {
            log.error("classId转换失败：{}", e.getMessage());
            return false;
        }
    }

    @DeleteMapping("/{classId}")
    public void deleteByClassId(@PathVariable String classId) {
        skuClassService.deleteByClassId(Integer.parseInt(classId));
    }


}
